package concurrency.part1.task3;


import java.util.ArrayList;
import java.util.List;

public class Buffer<T> {
    private int size;
    private int startIndex;
    private int endIndex;
    private List<T> buffer;
    private final int MAX_SIZE;
    public Buffer(int maxSize) {
        buffer=new ArrayList<T>(maxSize);
        //для того что бы при 32:buffer.set(endIndex,t); не было ошибок
        for (int i = 0; i < maxSize; i++)
            buffer.add(null);
        MAX_SIZE = maxSize;
        size=0;
        startIndex=endIndex=0;
    }

    public synchronized void add(T t){
        while (isFull()){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        endIndex=nextIndex(endIndex);
        buffer.set(endIndex,t);
        size++;
        notifyAll();
    }

    public synchronized T get(){
        while (isEmpty()) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        T res= buffer.get(startIndex);
        startIndex=nextIndex(startIndex);
        size--;
        notifyAll();
        return res;
    }

    public synchronized T peek(){
        if (isEmpty())
            return null;
        else
            return buffer.get(startIndex);
    }

    private boolean isEmpty(){
        return size==0;
    }

    private boolean isFull(){
        return size==MAX_SIZE;
    }

    private int nextIndex(int index){
        return (index+1)%MAX_SIZE;
    }
}
